package com.spider.silence.output;

import com.google.common.collect.Lists;
import com.spider.silence.utils.PropertiesUtil;

import java.util.LinkedList;

/**
 * @author 夏茂轩
 * @package com.spider.silence.output
 * @Date 2017/2/9 20:05
 */
public class MongoWriterPool {
    private static MongoWriterPool  instance= new MongoWriterPool();
    protected LinkedList<MongoWriter> pool = Lists.newLinkedList();

    private MongoWriterPool() {
        synchronized (pool){
            for(int i = 0; i<Integer.valueOf(PropertiesUtil.getVal("main.mongo.writer.pool.size")); i++){
                MongoWriter writer =new MongoWriter();
                pool.add(writer);
            }
            pool.notifyAll();
        }
    }
    public  void releaseWriter(MongoWriter writer) {
        if (writer != null) {
            synchronized (pool) {
                pool.addLast(writer);
                pool.notifyAll();
            }
        }
    }


    public  static MongoWriterPool getInstance(){
        return  instance;
    }
    /**
     * @author 夏茂轩
     * @date 2017/2/9 20:07
     * @description
     * @return
     * @throws InterruptedException
     */
    public  MongoWriter fetchWriter() throws InterruptedException {
        synchronized (pool){
            while (pool.isEmpty()){
                pool.wait();
            }
            return pool.removeFirst();
        }
    }
}
